package dao;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtils{
	private static SessionFactory sf=null;
	static{
		//1.创建Configuration,该对象用于读取hibernate.cfg.xml,并完成初始化
		Configuration cfg=new Configuration();
		cfg.configure();
		//2.创建SessoinFactory[这是一个会话工厂，是一个重量级的对象
		ServiceRegistry  sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();           
		sf = cfg.buildSessionFactory(sr);  
	}
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	public static SessionFactory getSessionFactory() {
		return sf;
	}	

	public static Session getSession(){
		Session session = (Session) threadLocal.get();
		if (session == null){
			session = sf.openSession();
			threadLocal.set(session);
		}
	        return session;
	}
	
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
        if (session != null)
        	session.close();
        threadLocal.set(null);
    }
	
	public static void shutdown(){
		getSessionFactory().close();
	}

}